
package ca.etsmtl.logti.log619.lab05.filter;

import java.util.Enumeration;

import javax.mail.internet.MimeMessage;

public class LocalIPAddressFilter implements EmailFilter {

    @Override
    public String getFilterName() {
        return getClass().getSimpleName();
    }

    @Override
    public byte checkSpam(MimeMessage message) {
        try {
            @SuppressWarnings("unchecked")
			Enumeration<String> lines = message.getAllHeaderLines();
            while (lines.hasMoreElements()) {
                String line = lines.nextElement();
                String ip = extractIP(line);
                if (ip != null) {
                    if (ip.startsWith("192.168")) {
                        return -5;
                    } else {
                    	return 0;
                    }
                }
            }
            return 0;
        } catch (Exception e) {
        }
        return 0;
    }

    public String extractIP(String line) {

        int pos;
        String ip;

        // try ([n.n.n.n])
        if ((pos = line.indexOf("[")) > 0) {
            ip = line.substring(pos + 1);

            if ((pos = ip.indexOf("]")) > 0) {
                ip = ip.substring(0, pos);
            }
            return ip;
        }
        return null;
    }

    @Override
    public boolean enabled() {
        return false;
    }

    @Override
    public byte getConfidenceLevel() {
        return 80;
    }
}
